<% 
local json = require "luci.json"
local uci = require "luci.model.uci".cursor()
local fs = require "nixio.fs"
local http = require "luci.http"
uci:load("lorasrv")

local devs = uci:get_list("lorasrv",self.app_id, "device")
local dsp = require "luci.dispatcher"
--local start  = luci.http.formvalue("s") 
local limit = luci.http.formvalue("l") 
local page = luci.http.formvalue("p") 
local rm = luci.http.formvalue("rm")
local find = luci.http.formvalue("find")
limit = limit and tonumber(limit) or 10
page = page and tonumber(page) or 1

local start = (page - 1) * limit + 1

if find then
	local find_devs = {}
	for i, dev in ipairs(devs) do

		if string.find(dev,find) ~= nil then
			find_devs[#find_devs+1] = dev
		end
	end
	devs = find_devs
end

if rm then
	local tar_eui = luci.http.formvalue("eui")
	local rm_eui = devs[tonumber(rm)]
	if tar_eui == rm_eui then
		table.remove(devs, tonumber(rm))
		if #devs == 0 then
			uci:delete("lorasrv", self.app_id, "device")
		else
			uci:set_list("lorasrv", self.app_id, "device", devs)
		end
		uci:delete("lorasrv", rm_eui)
		uci:save("lorasrv")
	end
end


%>
<% if http.formvalue("err") == "dup" then %>
<script type="text/javascript">
	$(document).ready(function(){
		openAlert("Error", "LoRa Device already exists");
	});
	
</script>
<% end %>
<style type="text/css">
#_import_dev_p_i{
	background: #0069d6;
	border-radius: 4px;
	color:#fff;
}
</style>
<% if fs.access("/tmp/.tmp_import_device_file") then %>

<script type="text/javascript">
	$(document).ready(function(){
		openModal("Alert","\
			<div style='width:100%;text-align:center'>Import is processing ...</div>\
			<div id='_import_dev_p_o'><div id='_import_dev_p_i' style='width:0%'>0%</div></div>	\
			");
		var intv = setInterval(function(){
			$.ajax({
				url : '<%=dsp.build_url("admin","loraserver","app","import_status")%>',
				type: 'get',
				dataType : 'json',
				success : function(data){
					
					if( data.total != 0 ){
						var p = "" + (data.done * 100 / data.total ).toFixed(0) +"%";
						console.log(p);
						$("#_import_dev_p_i").css("width", p);
						$("#_import_dev_p_i").html(p);
					}
					else{
						$("#_import_dev_p_i").css("width", "100%");
						$("#_import_dev_p_i").html("100%");
						clearInterval(intv);
						setTimeout(function(){
							window.location.reload();
						}, 1000)
						
					}
					
				},
				error: function(err){
					console.log(err);
				}
			})

		}, 1000);

	})
</script>
<% end %>
<script type="text/javascript">
	$(document).ready(function(){
		$("#batch_remove").click(function(){
			var uri = '<%=dsp.build_url("admin","loraserver","app","batch_remove",self.app_id)%>' + "?p=<%=page%>&l=<%=limit%>&find=<%=find%>"
			$(".rmcbx").each(function(index,ele){
				if( ele.checked ){
					uri += "&eui="+$(ele).attr("data")
				}
			})
			location = uri;
		})
		$("#select_all").click(function(){
			console.log("aaa");
			var c = false;
			$(".rmcbx").each(function(a,b){
				if( !b.checked )
				{
					c = true;
				}
			})
			$(".rmcbx").each(function(a,b){
				b.checked = c;
			});
		});
		$("#find_btn").click(function(){
			var eui = $("#find_dev").val();
			
			location = "<%=REQUEST_RUI%>?find="+eui;
		})
	})
	function remove(id,name,idx){
		if( confirm("<%:Confirm to remove device %>" + name))
		{
			var uri = '<%=dsp.build_url("admin","loraserver","app","batch_remove",self.app_id)%>' + "?p=<%=page%>&l=<%=limit%>&find=<%=find%>&eui="+id
			
			location = uri;
		}
	}
</script>
<style type="text/css">
	th>i.fa{
		color:#0069d6;
		margin-right:4px;
	}
</style>

<table class="cbi-section-table table table-stripted">
	<tbody>
		<tr>
			<th></th>
			<th></th>
			<th><%:Last seen%></th>
			<th><%:Device name%></th>
			<th><%:Device EUI%></th>
			<th><%:Class%></th>
			<th><%:Activation mode%></th>
			<th><%:Device Address%></th>
			<th><%:Link margin%></th>
			<th><%:Battery%></th>
			<th><%:Packet Loss%></th>
			<th><%:Description%></th>
			<th></th>
		</tr>
		
		<% 
		local dev = ""
		local t
		local send = (( start + limit - 1 ) < #devs) and (start + limit - 1) or #devs
		for i = start, send do
		t = uci:get_all("lorasrv", devs[i])
		if t then
		local live_info = luci.util.exec("srvctrl -d %s" % { devs[i] })
		local live_obj = luci.json.decode(live_info);
		local live_data = live_obj and live_obj["data"]
		local last_seen_s = live_data and live_data["last_seen"] or 0
		local last_seen = ""

		if last_seen_s == 0 then
		last_seen = "never"
		else
		local diffs = os.time() - last_seen_s
		if diffs < 60 then
		last_seen = diffs .. " seconds ago"
		elseif diffs < 3600 then
		last_seen = math.modf(diffs/60) .. " minutes ago"
		elseif diffs < 3600*24 then
		last_seen = math.modf(diffs/3600) .. " hours ago"
		elseif diffs < 3600*24*7 then
		last_seen = math.modf(diffs/(3600*24)) .. " days ago"
		elseif diffs < 3600*24*30 then
		last_seen = math.modf(diffs/(3600*24*7)) .. " weeks ago"
		else
		last_seen = math.modf(diffs/(3600*24*30)) .. " months ago"
		end

		end

		local dev_addr = live_data and live_data.dev_addr or "-"
		if dev_addr == "FFFFFFFF" or dev_addr == "ffffffff" then
		dev_addr = "-"
		end
		local margin = live_data and live_data.margin or "-"
		local battery = live_data and live_data.battery or "-"
		local stat = live_data and live_data["stat"]

		%>
		<tr>
			<td><input type="checkbox" class="rmcbx" data="<%=devs[i]%>" /></td>
			<td><%=i%></td>
			<td id="last_seen_<%=i%>"><%=last_seen%></td>
			<td><a href="<%=dsp.build_url("admin", "loraserver", "app","edit_device",self.app_id,devs[i])%>" ><%=pcdata(t.name)%></a></td>
			<td><a href="<%=dsp.build_url("admin", "loraserver", "app","edit_device",self.app_id,devs[i])%>" ><%=pcdata(string.lower(devs[i]))%></a></td>
			<td><%=(t.Class or "A")%></td>
			<td><%=t.mode%></td>
			<td id="dev_addr_<%=i%>"><%=dev_addr%></td>

			<td><%=margin%>dB</td>
			<td><%if battery == '-' then
				-%>-<%-
				elseif battery == 0 then
				-%>
				<i class="fa fa-plug"></i>
				<%-else-%>

				<%=pcdata(math.modf(battery*100/254))%>%
				<%-end%></td>
				<td><%if stat then -%><%=string.format("%.2f" ,(stat.lost * 100)/(stat.total_up + stat.lost))%>%<%-end%></td>
				<td><%=t.description%></td>
				<td>
					<a href="<%=dsp.build_url("admin", "loraserver", "app","edit_device",self.app_id,devs[i])%>" ><i class="fa fa-pencil-square-o" title="Edit" style="font-size:18px;margin-right:8px;color:#26b0f1"></i></a>
					<span onclick='remove("<%=devs[i]%>","<%=t.name%>","<%=i%>")'><i class="fa fa-remove" style="font-size:18px;color:red" title="remove"></i></span>
				</td>
			</tr>
			<%
			end
			end
			%>

		</tbody>

	</table>
	<style type="text/css">
		.table-action > div{
			float:right;
		}
		#find_dev{
			border-right:none;
		    margin: 0;
		    height: 29px;
		    padding: 2px;
		}
		#find_dev+button{
			border-left:none;
			background: #eee;
		}
	</style>
	<div style="float:left;width: 50%" class="table-action">
		<button class="btn btn-small"  type="button" id="select_all" ><%:Select All%></button>
		<button class="btn btn-small" id="batch_remove"  type="button" ><%:Remove%></button>
		<input type="text" id="find_dev" value="<%=find%>" placeholder="<%:Device EUI%>" ><button class="btn btn-small" id="find_btn" type="button"><i class="fa fa-search"></i></button>
	</div>
	<div style="float:right;width: 50%" class="table-action">

	<script type="text/javascript">
		function climit(){
			location = "<%=REQUEST_RUI%>?p=1&l="+$("#limit").val();
		}

		function prev(){
			if( <%=page%> == 1 )
				return false
			location = "<%=REQUEST_RUI%>?p=<%=pcdata(page-1)%>"+"&l="+$("#limit").val()+"&find=<%=find%>";
		}
		function next(){
			location = "<%=REQUEST_RUI%>?p=<%=pcdata(page+1)%>"+"&l="+$("#limit").val()+"&find=<%=find%>";
		}
		function topage(){
			location = "<%=REQUEST_RUI%>?p=" + $("#lpage").val()+"&l="+$("#limit").val()+"&find=<%=find%>";
		}
	</script>

	<div>
		<button class="btn btn-small"  type="button" onclick="prev()" >Prev</button>
		<button class="btn btn-small" type="button" onclick="next()">Next</button>
	</div>
	<div>
		<label>Page <input type="number" id="lpage" value="<%=pcdata(page)%>" style="width:48px" onchange="topage()" > In <%=pcdata(math.modf( #devs/limit ) + (math.fmod(#devs,limit) > 0 and 1 or 0) )%></label>
	</div>
	<div>
		<label>Rows per page</label>
		<select id="limit" onchange="climit()" style="width:60px">
			<option value="10" <%=pcdata(limit == 10 and "selected")%> >10</option>
			<option value="20" <%=pcdata(limit == 20 and "selected")%> >20</option>
			<option value="50" <%=pcdata(limit == 50 and "selected")%> >50</option>
			<option value="100" <%=pcdata(limit == 100 and "selected")%> >100</option>
		</select>
	</div>
	
</div>

<div style="margin-top:8px;float:left">
	<script type="text/javascript">
		function add_devices(){
			var reg = /^[0-9a-fA-F]{16}$/;

			var name = $("#app_add_dev_name").val();
			if( !reg.test(name)){
				alert("Device EUI format error!");
				return;
			}
			location="<%=dsp.build_url("admin", "loraserver","app","add_device")%>"+"?name="+name+"&app=<%=self.app_id%>";
		}
		function batch_add_devices(){
			location = "<%=dsp.build_url("admin","loraserver","app", "batch_add_device") .. "?app=" .. self.app_id %>"
		}
		function export_devices(){
			window.location = "<%=dsp.build_url("admin", "loraserver", "app","export", self.app_id)%>"
		}
	</script>
	<input type="text" placeholder="<%:please input device EUI%>" class="cbi-section-create-name" id="app_add_dev_name">
	<input class="cbi-button cbi-button-add"  type="button" onclick="add_devices()" value="<%:Add%>" title="<%:Add%>">
	<input class="cbi-button cbi-button-add"  type="button" onclick="batch_add_devices()" value="<%:Batch Add%>" title="<%:Batch Add%>">
	
	<script type="text/javascript">
		function import_device() {
			openModal("Import Devices","\
				<form action='<%=dsp.build_url('admin', 'loraserver','app','import', self.app_id)%>'  \
				method='post' enctype='multipart/form-data' >\
				<div class='cbi-value'>\
				<label class='cbi-value-title' >Please select the file to import</label> \
				<div class='cbi-value-field'> \
				<input type='file' name='import_devices' >				\
				<input type='submit' value='<%:Submit%>'> \
				</div> \
				</div> \
				</form>")
			
		}
	</script>

	<input type="button" id="_import_button" class="cbi-button cbi-button" value="<%:Import%>" name="import" onclick="import_device()">
	<input type="button" class="cbi-button cbi-button" value="<%:Export%>" name="export" onclick="export_devices()" />

</div>
